package org.liuyuantao.lucene.parser;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;

public class CustomParserUtil {

    public void searcherByQuery(Directory directory, String value) {
        try {
            IndexSearcher searcher = new IndexSearcher(DirectoryReader.open(directory));
            TopDocs tds = null;
            CustomParserExample parser = new CustomParserExample("content", new StandardAnalyzer());
            Query queryStr = parser.parse(value);
            System.out.println(queryStr);
            tds = searcher.search(queryStr, 50);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            for (ScoreDoc sd : tds.scoreDocs) {
                Document d = searcher.doc(sd.doc);
                System.out.println(sd.doc + ":(" + sd.score + ")" +
                        "[" + d.get("filename") + "【" + d.get("path") + "】--->" +
                        d.get("size") + "-----" + sdf.format(new Date(Long.valueOf(d.get("date")))) + "]");
            }
        } catch (NumberFormatException | IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            System.err.println(e.getMessage());
        }
    }
}
